package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.ClearCache;
import com.cy.pj.common.annotation.RequiredCache;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.Node;
import com.cy.pj.sys.dao.SysDeptDao;
import com.cy.pj.sys.entity.SysDept;
import com.cy.pj.sys.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SysDeptServiceImpl implements SysDeptService {
    @Autowired
    private SysDeptDao sysDeptDao;

    @RequiredCache
    @Override
    public List<Map<String, Object>> findObject() {
        List<Map<String, Object>> list = sysDeptDao.findObject();
        if(list == null || list.size() == 0)
            throw new ServiceException("没有对应的部门信息");
        return list;
    }

    @ClearCache
    @Override
    public int deleteObject(Integer id) {
        if(id == null || id < 1)
            throw new IllegalArgumentException("请先选择");
        int rows = sysDeptDao.deleteObject(id);
        if(rows == 0)
            throw new ServiceException("此纪录可能已经不存在");
        // TODO 删除部门时，更新用户的部门信息为null
        return rows;
    }

    @Override
    public List<Node> findZTreeNodes() {
        List<Node> list = sysDeptDao.findZTreeNodes();
        return list;
    }

    @ClearCache
    @Override
    public int saveObject(SysDept entity) {
        if(entity == null)
            throw new IllegalArgumentException("部门信息不能为空");
        if(entity.getName() == null || entity.getName() == "")
            throw new IllegalArgumentException("部门名称不能为空");
        int rows = sysDeptDao.insertObject(entity);
        if(rows == 0)
            throw new ServiceException("保存失败");
        return rows;
    }

    @ClearCache
    @Override
    public int updateObject(SysDept entity) {
        if(entity == null)
            throw new IllegalArgumentException("部门信息不能为空");
        if(entity.getName() == null || entity.getName() == "")
            throw new IllegalArgumentException("部门名称不能为空");
        int rows = sysDeptDao.updateObject(entity);
        if(rows == 0)
            throw new ServiceException("修改失败");
        return rows;
    }
}
